﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Text;
using Portal.Environment;
using Portal.Language;
using Portal.Interface;
using Portal.Framework;
using System.Collections.ObjectModel;
using System.IO;

namespace Portal.CMS
{
    public class RssChanelInfo
    {
        public string Url;
        public string SavedFile;
    }


    public class RssItemCls
    {
        public string ItemTitle;
        public string ItemDescription;
        public string Itemlink;
        public DateTime ItemPubDate;
        public RssItemCls(
            string _ItemTitle, 
            string _ItemDescription, 
            string _ItemLink, 
            DateTime _ItemPubDate)
        {
            ItemTitle = _ItemTitle;
            ItemDescription = _ItemDescription;
            Itemlink = _ItemLink;
            ItemPubDate = _ItemPubDate;
        }
    }


    public class RssChannelBll
    {
        public static string GetRssXmlData(
            string Title,
            string Description,
            string Link,
            string CopyRight,
            string Generator,
            DateTime PubDate,
            DateTime LastBuildDate,
            Collection<RssItemCls> RssItems)
        {
            if (RssItems == null) RssItems = new Collection<RssItemCls> { };
            string XmlData =
              "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n" +
              "<rss version=\"2.0\">\r\n" +
              "<channel>\r\n" +
              "  <title>" + Title + "</title>\r\n" +
              "  <description>" + Description + "</description>\r\n" +
              "  <link>" + Link + "</link>\r\n" +
              "  <copyright>" + CopyRight + "</copyright>\r\n" +
              "  <generator>" + Generator + "</generator>\r\n" +
              "  <pubDate>" + PubDate.ToString() + " GMT" + "</pubDate>\r\n" +
              "  <lastBuildDate>" + LastBuildDate.ToString() + " GMT" + "</lastBuildDate>\r\n";
            for (int iIndex = 0; iIndex < RssItems.Count; iIndex++)
            {
                XmlData +=
                    "<item>\r\n" +
                    "    <title><![CDATA[ " + RssItems[iIndex].ItemTitle + " ]]></title>\r\n" +
                    "    <description><![CDATA[ <a href=\"" + RssItems[iIndex].Itemlink + "\"></a>" + RssItems[iIndex].ItemDescription + " ]]></description>\r\n" +
                    "    <link>" + RssItems[iIndex].Itemlink + "</link>\r\n" +
                    "    <pubDate>" + RssItems[iIndex].ItemPubDate.ToString() + " GMT</pubDate>\r\n" +
                    "</item>\r\n";
            }
            XmlData +=
                "  </channel>\r\n" +
                "</rss>\r\n";
            return XmlData;
        }

        public static RssChanelCls[] GetRssChannel(string Ext)
        {
            string Query = "select GroupNewsItemId,GroupNewsItemAlias,Subject=["+Environments.ActiveLanguage+"GroupNewsItemName]  from TableGroupNewsItem where AllowRss=1";
            SqlConnection sqlConnection = new SqlConnection(Environment.Environments.ConnectionString);
            sqlConnection.Open();
            SqlCommand sqlCommand = sqlConnection.CreateCommand();
            sqlCommand.CommandText = Query;
            DataTable dtResult = new DataTable();
            SqlDataAdapter da = new SqlDataAdapter(sqlCommand);
            da.Fill(dtResult);

            RssChanelCls[] rssChannels = new RssChanelCls[dtResult.Rows.Count];
            for (int iIndex = 0; iIndex < rssChannels.Length; iIndex++)
            {
                string GroupNewsItemId = (string)dtResult.Rows[iIndex]["GroupNewsItemId"];
                string Subject = (string)dtResult.Rows[iIndex]["Subject"];
                string GroupNewsItemAlias = (string)dtResult.Rows[iIndex]["GroupNewsItemAlias"];
                if (String.IsNullOrEmpty(GroupNewsItemAlias))
                {
                    GroupNewsItemAlias = Environments.ConvertToLatinText(Subject);
                }
                RssChanelCls oRssChanelCls = new RssChanelCls(GroupNewsItemId, Subject, "", "","");
                oRssChanelCls.ChanelUrl = Environments.HttpWorkingRoot + "/Rss/" + GroupNewsItemAlias + "." + Ext;
                oRssChanelCls.ChanelSavePath = Environments.WorkingPath + "\\Rss";
                oRssChanelCls.ChanelSaveFile = Environments.WorkingPath + "\\Rss\\" + GroupNewsItemAlias + "." + Ext;
                
                rssChannels[iIndex] = oRssChanelCls;
            }
            return rssChannels;
        }

        public RssChanelInfo MakeXmlDataForChanel(
            string Title,
            string Description, 
            string Link, 
            string CopyRight, 
            string Generator, 
            DateTime PubDate,
            DateTime LastBuildDate,
            string ChanelId,
            string Ext)
        {
            if (Ext == null) Ext = "rss";
            RssChanelCls[] rssChannels = GetRssChannel(Ext);
            for (int iIndex = 0; iIndex < rssChannels.Length; iIndex++)
            {
                if (rssChannels[iIndex].ChanelId.Equals(ChanelId))
                {
                    RssChanelCls FoundRssChanel=rssChannels[iIndex];
                    string XmlSaveFile = FoundRssChanel.ChanelSaveFile;
                    DataTable dtGroupNewsItem = new NewsBLL().ReadingForRss(FoundRssChanel.ChanelId,30);
                    Collection<RssItemCls> RssItems = new Collection<RssItemCls> { };
                    for (int iIndexNews = 0; iIndexNews < dtGroupNewsItem.Rows.Count; iIndexNews++)
                    {
                        string belongSite=(string)dtGroupNewsItem.Rows[iIndexNews]["belongSite"];
                        string _ItemTitle=(string)dtGroupNewsItem.Rows[iIndexNews]["Subject"];
                        string _ItemDescription=(string)dtGroupNewsItem.Rows[iIndexNews]["ShortContent"];
                        string ShortId=(string)dtGroupNewsItem.Rows[iIndexNews]["ShortId"];
                        string _ItemLink=Environments.GetNewsUrl(belongSite, ShortId,_ItemTitle,"_runtime");
                        DateTime _ItemPubDate=(DateTime)dtGroupNewsItem.Rows[iIndexNews]["EntryDate"];
                        RssItems.Add(new RssItemCls(_ItemTitle,_ItemDescription,_ItemLink,_ItemPubDate));
                    }
                    string Xml=GetRssXmlData(Title, Description, Link, CopyRight, Generator, PubDate, LastBuildDate, RssItems);
                    RssChanelInfo RssChanelInfo = new RssChanelInfo();
                    RssChanelInfo.SavedFile = FoundRssChanel.ChanelSaveFile;
                    RssChanelInfo.Url = FoundRssChanel.ChanelUrl;

                    FileStream fs = new FileStream(RssChanelInfo.SavedFile, FileMode.Create);
                    StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
                    sw.Write(Xml);
                    sw.Close();

                    return RssChanelInfo;
                }
            }
            throw new Exception("Không tìm thấy kênh thông tin Rss!");
        }
    }
}
